package com.fandou.base.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;
import android.widget.LinearLayout;

import androidx.annotation.Nullable;

import com.fandou.base.R;

public class RatingBarView extends LinearLayout {
    private int maxNum;
    private int progress;
    private Drawable ratingBackground;
    private Drawable ratingProgress;
    private float itemWidth;
    private float itemHeight;
    private float ratingSpace;

    public RatingBarView(Context context) {
        this(context, null);
    }

    public RatingBarView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RatingBarView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initParams(context, attrs);
    }

    private void initParams(Context context, @Nullable AttributeSet attrs) {
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.RatingBarView);
        maxNum = typedArray.getInt(R.styleable.RatingBarView_maxNum, 5);
        progress = typedArray.getInt(R.styleable.RatingBarView_currentProgress, 0);
        ratingBackground = typedArray.getDrawable(R.styleable.RatingBarView_ratingBackground);
        ratingProgress = typedArray.getDrawable(R.styleable.RatingBarView_ratingProgress);
        itemWidth = typedArray.getDimension(R.styleable.RatingBarView_itemWidth, -1);
        itemHeight = typedArray.getDimension(R.styleable.RatingBarView_itemHeight, -1);
        ratingSpace = typedArray.getDimension(R.styleable.RatingBarView_ratingSpace, 0);
        typedArray.recycle();

        for (int i = 0; i < maxNum; i++) {
            ImageView imageView = new ImageView(context);
            LayoutParams layoutParams = new LayoutParams(Math.round(itemWidth), Math.round(itemHeight));
            if (i > 0) {
                if (getOrientation() == HORIZONTAL) {
                    layoutParams.leftMargin = Math.round(ratingSpace);
                } else {
                    layoutParams.topMargin = Math.round(ratingSpace);
                }

            }
            imageView.setLayoutParams(layoutParams);
            imageView.setImageDrawable(i < progress ? ratingProgress : ratingBackground);

            addView(imageView);
        }
    }

    public void setProgress(int progress) {
        if (progress > maxNum) {
            progress = maxNum;
        }
        for (int i = 0; i < maxNum; i++) {
            ImageView imageView = (ImageView) getChildAt(i);
            imageView.setImageDrawable(i < progress ? ratingProgress : ratingBackground);
        }
    }

    private void log(String log) {
        com.fandou.base.utils.FdLog.e(getClass().getSimpleName(), log);
    }
}
